﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logistics.Commn;
using Logistics.Model;
using Newtonsoft.Json;
using Logistics.SignIn;

namespace MyMiddleware
{
    /// <summary>
    /// 请求与返回中间件
    /// </summary>
    public class RequestResponseLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ISignInRepository _signInRepository;

        /// <summary>
        /// 
        /// </summary> 
        public RequestResponseLoggingMiddleware(RequestDelegate next, ISignInRepository signInRepository)
        {
            _next = next;
            _signInRepository = signInRepository;
        }

        /// <summary>
        /// 添加登录日志
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path.ToString().ToLower();
        
            if (path.ToUpper() == "/RBAC/INDEX")
            {
                var Log = new UserLog()
                {
                    UserId = RedisHelper.Get<Operator>("Operator").Id,
                    IpAdress = (await System.Net.Dns.GetHostEntryAsync(System.Net.Dns.GetHostName())).AddressList
                        .FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        ?.ToString(),
                    ThisLoginTime = DateTime.Now
                };
                _signInRepository.LoginLog(Log);
                await _next(context);
               
            }
            await _next(context);
        }

    }
}